* Initialize simulation batch naming
global batchrun `1'
global wagechange `2'
global stocks `3'
global spill `4'

set seed 182

*set which parts we recompute based on the input to the file
if ("$stocks" == "recompute") global stocksn rc
if ("$stocks" == "keep") global stocksn k
if ("$spill" == "recompute") global spilln rc
if ("$spill" == "keep") global spilln k

*make sure wagechange is not a string and store its value
global swagechange = subinstr("$wagechange", ".", "", .)
if ustrregexm("${wagechange}", "^[\d.]+") {
    global wagechange_amount = ustrregexs(0)
}

*if we do not recompute the spillovers, no need to indicate a 
*trunctuation for the multiplier or the distributing weights
*as we are obviously not doing them.
if ("$spill" != "recompute") global osmtrim ""
if ("$spill" != "recompute") global iwvers ""


global lname l${stocksn}${spilln}${swagechange}${iwvers}${osmtrim}${batchrun}
global bname ${ln_vers}pauto95_${chosen_spec}${FE}_${stocks}${spill}_${swagechange}_${iwvers}${osmtrim}_batch${batchrun}
global sname ${ln_vers}pauto95_${chosen_spec}${FE}_${stocks}${spill}_${swagechange}_${iwvers}${osmtrim}

if ("$spill" != "recompute") global bname ${ln_vers}pauto95_${chosen_spec}${FE}_${stocks}${spill}_${swagechange}_batch${batchrun}
global loginfo "Eq: [$chosen_spec, $FE, $ln_vers]. Data: [auto95, pauto95]. Stock-Spill: [$stocks, $spill]. Spill-version: [$iwvers $osmtrim]. Wagechange: [$wagechange]. Batch: [$batchrun, $N runs]"

* Define/build out-path (depending on whether we're recomputing spillovers or not)
global outd ${outdr}
if ("$spill" != "recompute") global outd ${outdk}
cap shell mkdir "$outd/data"
cap shell mkdir "$outd/log"
if ("$spill" == "recompute") cap shell mkdir "${outd}/result"

* Prepare splevelup program 
do ${d}code/macrosim/helper.do

* Get list of Bvd-ctry combinations (pre and updating weight)
*and create a list of all firm-country combinations for which we have weights
if "$spill" == "recompute" { 

    use BvD ctry using ${d}datasets/macrosim/bvd_ctry_year_inventor_weights${iwvers}_long.dta, clear
    duplicates drop

    mmerge BvD ctry using ${d}datasets/macrosim/bvd_ctry_inventor_weightspre_long.dta, unmatched(both) ukeep(ctry BvD)
    drop _m
    bys BvD: gen ctryid = _n
    tempfile bvdctry
    save `bvdctry', replace
}

* Load the dataset (and when we recompute spillovers, restrict to the firms with weights)
use ${d}datasets/macrosim/BvD_year_div_${ln_vers}_pauto95_${chosen_spec}.dta, clear
if "$spill" == "recompute" { 

    preserve
    keep BvD year firm_division
    mmerge BvD using `bvdctry', unmatched(master) 
    assert _m == 3
    keep firm_division year ctry ctryid
    save ${d}datasets/macrosim/BvD_ctry_year_div_list_${ln_vers}pauto95_${iwvers}${osmtrim}.dta, replace
    restore
}

cap erase ${outd}/data/batchruns_${bname}.dta